import os
import sys
import glob
import requests
import wenxin_api
from wenxin_api.tasks.text_to_image import TextToImage

wenxin_api.ak = "********************************"
wenxin_api.sk = "********************************"

class MV:
    def __init__(self):
        self.styleDict = ["油画","水彩画","卡通","粉笔画","儿童画","蜡笔画"]
        
    def getImageDict(self, text, style):
        input_dict = {
            "text": text,
            "style": style,
        }
        return TextToImage.create(**input_dict)

    def readAndSave(self, imgDict, text=None, savedPath=None):

        haveSaved = len(glob.glob(os.path.join(savedPath, text+"_*.png")))

        for index, url in enumerate(imgDict['imgUrls']):
            r = requests.get(url)
            imgName = text + "_" + str(haveSaved + index) + '.png'
            out_ii = os.path.join(savedPath , imgName)
            with open(out_ii, 'wb') as f:
                f.write(r.content)
            f.close()

    def singleText(self, lrc=None, style=None, path=None):
        if path is None:
            return False
        if not os.path.exists(path):
            return False

        if style is None:
            style = "油画"
        
        idict = self.getImageDict(lrc, style)
        return idict
        # self.readAndSave(idict, text=lrc, savedPath=path)

    def make(self, lrc=None, songName=None, style=0, startindex=0):
        if style < 6 and style >= 0:
            self.style = self.styleDict[style]
        else:
            try:
                sys.exit(0)
            except:
                print("Wrong Style")

        self.lrcs = []

        if os.path.exists(lrc):
            with open(lrc, 'r', encoding='UTF-8') as fp:
                lines = fp.readlines()
                for line in lines:
                    self.lrcs.append(line)
        else:
            self.lrcs.append(lrc)

        print(self.lrcs)

        if songName is not None:
            self.songName = songName
        else:
            if os.path.exists(lrc):
                self.songName = os.path.basename(lrc).split(".")[0]
            else:
                self.songName = lrc
        os.makedirs(self.songName, exist_ok=True)
        
        for index, txt in enumerate(self.lrcs):
            print(index, txt)
            if index >= startindex:
                textlist = txt.split("@:")
                if len(textlist) > 1 and textlist[-1] is not '':
                    txt = textlist[-1]
                txt = txt.replace("\n", "")
                idict = self.getImageDict(txt,self.style)
                self.readAndSave(idict, text=txt)